import os

from django.db import models

from user.models import User


def get_item_image_name(instance, filename):
    extension = filename.split(".")[-1]
    # 生成新的文件名
    new_filename = f'{instance.id}_item_image.{extension}'
    # 返回新的文件名
    return os.path.join('item_images', new_filename)


class Item(models.Model):
    name = models.CharField("商品名", max_length=50, null=False)
    single_price = models.DecimalField("商品单价", null=False, max_digits=12, decimal_places=2)
    info = models.TextField("商品信息", null=True)
    shop = models.ForeignKey(User, verbose_name="商品所属商家", null=False, on_delete=models.CASCADE)
    item_image = models.ImageField(upload_to=get_item_image_name, null=True)


"""
订单的状态集合
"""
PREPARING = "P"
WAITING = "W"
DELIVERING = "D"
ARRIVED = "A"
FINISHED = "F"
COMMENTED = "C"


class Order(models.Model):
    STATE_CHOICES = (
        (PREPARING, "订单准备中"),
        (WAITING, "等待骑手接单中"),
        (DELIVERING, "订单派送中"),
        (ARRIVED, "订单已送达"),
        (FINISHED, "订单已完成"),
        (COMMENTED, "订单已被评价"),
    )

    item = models.ForeignKey(Item, null=False, verbose_name="选购商品", on_delete=models.CASCADE)
    num = models.PositiveIntegerField("购入数目", null=False)
    state = models.CharField("订单状态", null=False, default=WAITING, max_length=5, choices=STATE_CHOICES)
    rider = models.ForeignKey(User, verbose_name="订单骑手", on_delete=models.CASCADE, null=True, related_name='rider_orders')
    shop = models.ForeignKey(User, verbose_name="订单商家", on_delete=models.CASCADE, null=False, related_name='shop_orders')
    customer = models.ForeignKey(User, verbose_name="订单顾客", on_delete=models.CASCADE, null=False, related_name='customer_orders')
    address = models.CharField("订单地址", max_length=40, null=False)
    phonenum = models.CharField("订单电话", max_length=15, null=False)
    create_time = models.DateTimeField("创建时间", auto_now_add=True)


class Comment(models.Model):
    rating = models.DecimalField("订单评级", null=False, default=5.0, max_digits=4, decimal_places=1)
    comment = models.CharField("评价内容", null=False, max_length=256)
    create_time = models.DateTimeField("发布时间", auto_now_add=True)
    sender = models.ForeignKey(User, verbose_name="发布者", null=False, on_delete=models.CASCADE)
    item = models.ForeignKey(Item, verbose_name="相关商品", null=False, on_delete=models.CASCADE)

